package com.li.sparkstreaming

import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.kafka010.{ConsumerStrategies, KafkaUtils, LocationStrategies}
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
 * sparkstreaming与kafka整合
 */
object StreamKafka {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf();
    conf.setMaster("local[2]"); //local[2]表示启动两个进程，1个读取数据，一个处理数据
    conf.setAppName("StreamKafka");

    //创建StreamContext,指定数据处理间隔5s
    val streamingContext = new StreamingContext(conf, Seconds(5))

    //指定kafka配置信息
    val kafkaParams = Map[String, Object](
      //kafka地址信息
      "bootstrap.servers" -> "bigdata01:9092,bigdata02:9092,bigdata03:9092",
      //key value 序列化类型
      "key.deserializer" -> classOf[StringDeserializer],
      "value.deserializer" -> classOf[StringDeserializer],
      //消费者组id
      "group.id" -> "con_2",
      //消费策略
      "auto.offset.reset" -> "latest",
      //自动提交offset
      "enable.auto.commit" -> (true: java.lang.Boolean)
    )

    val topics = Array("t1")

    val kafkaStreaming = KafkaUtils.createDirectStream[String, String](streamingContext,
      LocationStrategies.PreferConsistent,
      ConsumerStrategies.Subscribe[String, String](topics, kafkaParams))


    kafkaStreaming.map(record => (
      record.key(), record.value()
    )).print()
    streamingContext.start();
    streamingContext.awaitTermination()
  }
}
